/************************************************************************
<4loco-aprs.  This program connects to a specified APRS server and displays
    the information on a map. It's being developed using QT Creator. The project
    began in February and version 1 should be released in April. For more
    information go to http://code.google.com/p/4loco-aprs/>

    Copyright (C) <2011>  <Kyle Roden, Glen Riden, Aaron Smith, Alisa Emerich>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#include "configstation.h"
#include "ui_configstation.h"
#include "stationsettings.h"
#include "errordialog.h"
#include <QDoubleValidator>
#include <QIntValidator>
#include <QString>

configStation::configStation(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::configStation)
{
    ui->setupUi(this);
    setWindowTitle("Configure Station");
    ui->viewSettingDB->hide();

    QDoubleValidator *latValidator = new QDoubleValidator(-90.0, 90.0, 4, this);
    latValidator->setRange(-90.0, 90.0, 4);
    latValidator->setNotation(QDoubleValidator::StandardNotation);
    ui->LE_DecLat->setValidator(latValidator);
    ui->LE_DMS_Lat_Deg->setValidator(latValidator);

    QDoubleValidator *longValidator = new QDoubleValidator(-180.0, 180.0, 4, this);
    longValidator->setRange(-180.0, 180, 4);
    longValidator->setNotation(QDoubleValidator::StandardNotation);
    ui->LE_DMS_Long_Deg->setValidator(longValidator);
    ui->LE_DecLong->setValidator(longValidator);

    QIntValidator *minSecValidator = new QIntValidator;
    minSecValidator->setRange(0, 60);
    ui->LE_DMS_Lat_Min->setValidator(minSecValidator);
    ui->LE_DMS_Lat_Sec->setValidator(minSecValidator);
    ui->LE_DMS_Long_Min->setValidator(minSecValidator);
    ui->LE_DMS_Long_Sec->setValidator(minSecValidator);

    // Signals and Slots
    selectStations = new stationsettings::stationsettings(this);
    selectStations->setModal(true);
    connect(selectStations,SIGNAL(symbolSelected(char)),this,SLOT(updateSymbol(char)));
    connect(ui->PB_SelectSymbol, SIGNAL(clicked()), this->selectStations, SLOT(exec()));
    connect(ui->viewSettingDB,SIGNAL(clicked()), this, SLOT(ViewSettingsDatabase()));
    connect(ui->PB_Save, SIGNAL(clicked()), this, SLOT(UpdateSettingsDatabase()));
    connect(ui->PB_Ok, SIGNAL(clicked()), this, SLOT(UpdateSettingsDatabase()));
    connect(ui->PB_Ok, SIGNAL(clicked()), this, SLOT(close()));
    connect(ui->RB_Decimal, SIGNAL(toggled(bool)), this, SLOT(DecimalPositionSelected()));
    connect(ui->RB_DMS, SIGNAL(toggled(bool)), this, SLOT(DMSPositionSelected()));
    connect(ui->PB_Cancel, SIGNAL(pressed()), this, SLOT(close()));
    connect(ui->usesqlcheckbox,SIGNAL(stateChanged(int)),this,SLOT(mySqlWarning(int)));

    //connect(ui->PB_SelectSymbol, SIGNAL(clicked()), this, SLOT(symbolSelected()));
    /*************SettingsDatabase*******************/
    settingsDatabase = QSqlDatabase::addDatabase("QSQLITE", "settings");
    settingsDatabase.setDatabaseName("../config.db");

    // MAKE SURE DATABASE OPENS SUCCESSFULLY
    if (!settingsDatabase.open())
    {
        qDebug() << "Database Error :: NEAR CONFIGSTATION.CPP LINE 53";
        qDebug() << settingsDatabase.lastError();
    }

  // QSqlQuery query(settingsDatabase);     //these two lines
//   query.exec("drop table settings");    // will help reset table if you add fields

    if (!settingsDatabase.tables().contains("settings")){

        CreateNewTable();
        ui->usesqlcheckbox->setChecked(false);
}
    else
        FillInValues();

}
void configStation::mySqlWarning(int state){

    if(state==0)
        return;
    ErrorDialog errorDialog(this);
    errorDialog.setModal(true);
    errorDialog.setErrorText("to enable MySQL:\ncomplete all fields below\n click save\nrestart the program ");
    errorDialog.exec();
}

configStation::~configStation()
{
    delete ui;
    settingsDatabase.close();  // close connection to the database
}

void configStation::DecimalPositionSelected()
{
    if (ui->RB_Decimal->isChecked())
    {
        ui->LE_DMS_Lat_Deg->setText("");
        ui->LE_DMS_Lat_Deg->setDisabled(true);
        ui->LE_DMS_Lat_Min->setText("");
        ui->LE_DMS_Lat_Min->setDisabled(true);
        ui->LE_DMS_Lat_Sec->setText("");
        ui->LE_DMS_Lat_Sec->setDisabled(true);
        ui->LE_DMS_Long_Deg->setText("");
        ui->LE_DMS_Long_Deg->setDisabled(true);
        ui->LE_DMS_Long_Min->setText("");
        ui->LE_DMS_Long_Min->setDisabled(true);
        ui->LE_DMS_Long_Sec->setText("");
        ui->LE_DMS_Long_Sec->setDisabled(true);

        ui->LE_DecLat->setEnabled(true);
        ui->LE_DecLong->setEnabled(true);
    }
}

void configStation::DMSPositionSelected()
{
    if (ui->RB_DMS->isChecked())
    {
        ui->LE_DecLat->setText("");
        ui->LE_DecLat->setDisabled(true);
        ui->LE_DecLong->setText("");
        ui->LE_DecLong->setDisabled(true);

        ui->LE_DMS_Lat_Deg->setEnabled(true);
        ui->LE_DMS_Lat_Min->setEnabled(true);
        ui->LE_DMS_Lat_Sec->setEnabled(true);
        ui->LE_DMS_Long_Deg->setEnabled(true);
        ui->LE_DMS_Long_Min->setEnabled(true);
        ui->LE_DMS_Long_Sec->setEnabled(true);
    }
}

void configStation :: FillInValues()
{
    QSqlQuery fillInQuery(settingsDatabase);

    fillInQuery.exec("SELECT * FROM settings;");

    while (fillInQuery.next())
    {
        ui->LE_CallSign->setText(fillInQuery.value(0).toString());
        ui->LE_SymbolCode->setText(fillInQuery.value(1).toString());
        ui->LE_Overlay->setText(fillInQuery.value(2).toString());
        ui->LE_Comment->setText(fillInQuery.value(3).toString());
        if (fillInQuery.value(4).toString() == "1")
        {   // Values are in decimal
            ui->RB_Decimal->setChecked(true);
            ui->RB_DMS->setChecked(false);
            ui->LE_DecLat->setText(fillInQuery.value(5).toString());
            ui->LE_DecLong->setText(fillInQuery.value(6).toString());
            ui->LE_DMS_Long_Sec->setText("");
            ui->LE_DMS_Lat_Deg->setText("");
            ui->LE_DMS_Lat_Min->setText("");
            ui->LE_DMS_Lat_Sec->setText("");
            ui->LE_DMS_Long_Deg->setText("");
            ui->LE_DMS_Long_Min->setText("");
        }
        else if (fillInQuery.value(4).toString() == "0")
        {
            ui->RB_Decimal->setChecked(false);
            ui->RB_DMS->setChecked(true);
            ui->LE_DecLat->setText("");
            ui->LE_DecLong->setText("");
            ui->LE_DMS_Lat_Deg->setText(fillInQuery.value(7).toString());
            ui->LE_DMS_Lat_Min->setText(fillInQuery.value(8).toString());
            ui->LE_DMS_Lat_Sec->setText(fillInQuery.value(9).toString());
            ui->LE_DMS_Long_Deg->setText(fillInQuery.value(10).toString());
            ui->LE_DMS_Long_Min->setText(fillInQuery.value(11).toString());
            ui->LE_DMS_Long_Sec->setText(fillInQuery.value(12).toString());

        }
        if(fillInQuery.value(13).toInt()==0)
            ui->usesqlcheckbox->setChecked(false);
        ui->server->setText(fillInQuery.value(14).toString());
        ui->port->setText(fillInQuery.value(15).toString());
        ui->dbname->setText(fillInQuery.value(16).toString());
        ui->username->setText(fillInQuery.value(17).toString());
        ui->password->setText(fillInQuery.value(18).toString());


    }
}
void configStation :: updateSymbol(char symbol){

    ui->LE_SymbolCode->setText(QString(symbol));

}

void configStation :: CreateNewTable()
{
    QSqlQuery popSetQuery(settingsDatabase);
    popSetQuery.exec("CREATE TABLE settings ("
                  "Call_Sign STRING, "
                  "Station STRING, "
                  "Overlay STRING, "
                  "Comment STRING, "
                  "Decimal_or_Degrees STRING, "
                  "Dec_Lat STRING, "
                  "Dec_Long STRING, "
                  "DMS_D_Lat STRING, "
                  "DMS_M_Lat STRING, "
                  "DMS_S_Lat STRING, "
                  "DMS_D_Long STRING, "
                  "DMS_M_Long STRING, "
                  "DMS_S_Long STRING,"
                  "usemysql int,"
                                    "server string,"
                                    "port string,"
                                    "dbname string,"
                                    "username string,"
                                    "password string"
                  ");");
    qDebug()<<popSetQuery.lastError()<<"create table error!";
    popSetQuery.exec("INSERT INTO settings VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);");
    qDebug() << popSetQuery.lastError()<<"init values error!";
}

void configStation :: UpdateSettingsDatabase()
{
    /******************** getData SLOT ********************
     THIS SLOT GETS THE DATA FROM CONFIGSTATIONS GUI
       AND STORES IT IN TO THE SETTINGS SQL DATABASE.
    ******************************************************/
    QSqlQuery updateData(settingsDatabase);
    updateData.prepare("UPDATE settings SET Call_Sign=?, Station=?, Overlay=?, Comment=?, Decimal_or_Degrees=?,"
                       "Dec_Lat=?,Dec_Long=?,DMS_D_Lat=?, DMS_M_Lat=?, DMS_S_Lat=?, DMS_D_Long=?,"
                       "DMS_M_Long=?, DMS_S_Long=?,"
                       "usemysql=?, server=?, port=?, dbname=?, username=?, password=?"

                       ";");
    updateData.addBindValue(ui->LE_CallSign->text());
    updateData.addBindValue(ui->LE_SymbolCode->text());
    updateData.addBindValue(ui->LE_Overlay->text());
    updateData.addBindValue(ui->LE_Comment->text());
    if (ui->RB_Decimal->isChecked())
    {
        updateData.addBindValue("1");
    }
    else
    {
        updateData.addBindValue("0");
    }
    updateData.addBindValue(ui->LE_DecLat->text());
    updateData.addBindValue(ui->LE_DecLong->text());
    updateData.addBindValue(ui->LE_DMS_Lat_Deg->text());
    updateData.addBindValue(ui->LE_DMS_Lat_Min->text());
    updateData.addBindValue(ui->LE_DMS_Lat_Sec->text());
    updateData.addBindValue(ui->LE_DMS_Long_Deg->text());
    updateData.addBindValue(ui->LE_DMS_Long_Min->text());
    updateData.addBindValue(ui->LE_DMS_Long_Sec->text());

       updateData.addBindValue(0);
        updateData.addBindValue(ui->server->text());
        updateData.addBindValue(ui->port->text());
       updateData.addBindValue(ui->dbname->text());
        updateData.addBindValue(ui->username->text());
        updateData.addBindValue(ui->password->text());
        if(!updateData.exec())
            qDebug()<<updateData.lastError();
        if(!(ui->usesqlcheckbox->isChecked()))

            return;

        updateData.prepare("update settings set usemysql=1;");

        updateData.exec();


}

void configStation :: ViewSettingsDatabase()
{
    /*** viewPacketDatabase SLOT ***
      THIS SLOT OPENS THE DATABASE
      QTABLEVIEW OF THE PACKETS
      DATABASE.
      **********************************************/
    QSqlQuery test(settingsDatabase);
    test.exec("SELECT * FROM settings;");
    QSqlQueryModel *testQ = new QSqlQueryModel;
    testQ->setQuery(test);
    QTableView *testView = new QTableView;
    testView->setModel(testQ);
    testView->setWindowTitle("Settings Database");
    testView->show();
}

